import React, { Component } from 'react'
import { nanoid } from 'nanoid'
import PropTypes from 'prop-types'

export default class Header extends Component {
  static propTypes = {
    addTask: PropTypes.func.isRequired
  }

  render() {
    return (
      <header className="header">
        <h1>todo-list</h1>
        <input onKeyUp={this.handleKeyUp} className="new-todo" placeholder="你想做点什么?" autoFocus />
      </header>
    )
  }

  handleKeyUp = (e) => {
    if (e.keyCode !== 13 || e.target.value.trim() === '') return
    const obj = {
      id: nanoid(),
      name: e.target.value,
      done: false
    }
    this.props.addTask(obj)
    e.target.value = ''
  }
}
